﻿/*  CamHelper (See http://camhelper.codeplex.com/ or https://bitbucket.org/AndiKS/camhelper for more Info)
    Copyright (C) 2011 Andreas Wimmer

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

using System;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using CamHelper.Interpreter;

namespace CamHelper.ProcessEditor
{
    public partial class CommandTesterControl : UserControl
    {
        private Parser _parser;
        private ArrayList _parserLog;
        private ArrayList _calculatorLog;
        private ConfigControl _config;

        public CommandTesterControl()
        {
            InitializeComponent();

            _parser = new Parser();
            _parser.Parsing += new EventHandler<ParseEventArgs>(_parser_Parsing);
            _parser.Parsed += new EventHandler<ParseEventArgs>(_parser_Parsed);
            _parser.Calculating += new EventHandler<ParseEventArgs>(_parser_Calculating);
            _parser.Calculated += new EventHandler<ParseEventArgs>(_parser_Calculated);

            lblResult.Text = String.Empty;
            if (!DesignMode)
                tabControl1.SelectedTab = tpCalculater;
        }

        #region Parser Events

        void _parser_Calculated(object sender, ParseEventArgs e)
        {
            var p = new
            {
                Command = e.Statement.Command,
                Calculated = e.Statement.CommandAfterCalculatedChild,
                Result = e.Statement.Result
            };
            _calculatorLog.Add(p);
        }

        void _parser_Calculating(object sender, ParseEventArgs e)
        {
            // Todo: Add to Result
        }

        void _parser_Parsed(object sender, ParseEventArgs e)
        {
            var p = new
            {
                StartToken = String.Format("{0} ('{1}')", e.Statement.StartToken, e.Parser.Tokens[e.Statement.StartToken]),
                EndToken = String.Format("{0} ('{1}')", e.Statement.EndToken, e.Parser.Tokens[e.Statement.EndToken]),
                Command = e.Statement.Command,
                Type = e.Statement.Name
            };
            _parserLog.Add(p);
        }

        void _parser_Parsing(object sender, ParseEventArgs e)
        {
            // Todo: Add to Result
        }

        #endregion

        private void txbCommand_TextChanged(object sender, System.EventArgs e)
        {
            flpParameter.Controls.Clear();

            IParameterCollection ps;
            if (cbxUseFiles.Checked)
                ps = _parser.SearchParameter(txbCommand.Text, _config.Parameter.AllParameter);
            else
                ps = _parser.SearchParameter(txbCommand.Text);

            foreach (var p in ps)
            {
                var field = new ParameterField(p.Value);
                field.ParameterChanged += new System.EventHandler(field_ParameterChanged);
                flpParameter.Controls.Add(field);
            }

            _parser.Parameter = ps;

            Calculate();
        }

        void field_ParameterChanged(object sender, System.EventArgs e)
        {
            Calculate();
        }

        #region Calculate

        void Calculate()
        {
            ClearResult();

            try
            {
                if (txbCommand.Text.Trim().Length > 0)
                {
                    lblResult.Text = _parser.Calc(txbCommand.Text);
                    lblResult.ForeColor = Color.DarkGreen;
                    ShowResult();
                }
                else
                    lblResult.Text = String.Empty;
            }
            catch (System.Exception)
            {
                lblResult.Text = "Error";
                lblResult.ForeColor = Color.DarkRed;
            }
        }

        #endregion

        #region Result

        void ShowResult()
        {
            var tokens = new ArrayList();
            for (int i = 0; i < _parser.Tokens.Count; i++)
            {
                var t = new { Index = i, Content = _parser.Tokens[i] };
                tokens.Add(t);
            }

            dgvToken.AutoGenerateColumns = true;
            dgvToken.DataSource = tokens;
            dgvToken.Visible = true;

            dgvParser.DataSource = _parserLog;

            dgvCalculator.DataSource = _calculatorLog;
        }

        void ClearResult()
        {
            dgvToken.Visible = false;
            _parserLog = new ArrayList();
            _calculatorLog = new ArrayList();
        }

        #endregion

        private void CommandTesterControl_Load(object sender, EventArgs e)
        {
            if (!DesignMode)
            {
                _config = ((MainForm)ParentForm).Config;
                _config.ConfigOrFilesChanged += new EventHandler(_config_ConfigOrFilesChanged);
            }
        }

        void _config_ConfigOrFilesChanged(object sender, EventArgs e)
        {
            throw new NotImplementedException();
        }

        private void cbxUseFiles_CheckedChanged(object sender, EventArgs e)
        {
            txbCommand_TextChanged(null, null);
        }
    }
}
